﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BlackBox.Models
{
    public class RatingRepository
    {

        DataClassesDataContext db = new DataClassesDataContext();

        //SingleTon patern
        public static GameRepository instance;


        public static GameRepository Instance
        {
            get
            {
                if (instance == null)
                    instance = new GameRepository();
                return instance;
            }
        }
        public void AddRating(Rating rating,int userId,int gameId)
        {
            RatingToUserToGame Relationship = new RatingToUserToGame
            {
                UserId = userId,
                Gameid = gameId,
            };
            Game game = (from x in db.Games
                         where x.id == gameId
                         select x).Single();
            db.RatingToUserToGames.InsertOnSubmit(Relationship);
            db.Ratings.InsertOnSubmit(rating);
            db.SubmitChanges();
        }
        public void removeRating(Rating ratingToBeDeleted)
        {
            RatingToUserToGame relationshipToBeDeleted = (from x in db.RatingToUserToGames
                                                          where x.RatingId == ratingToBeDeleted.id
                                                          select x).First();
            db.RatingToUserToGames.DeleteOnSubmit(relationshipToBeDeleted);
            db.Ratings.DeleteOnSubmit(ratingToBeDeleted);
            db.SubmitChanges();
        }
        public List<Rating> GetGameRating(int gameId)
        {
            var relationship = (from x in db.RatingToUserToGames
                                               where x.Gameid == gameId
                                               select x);
            List<Rating> returnList = new List<Rating>();
            foreach(var rating in relationship)
            {
                Rating temp = (from x in db.Ratings
                               where x.id == rating.RatingId
                               select x).Single();
                returnList.Add(temp);
            }
            return returnList;
        }
        public List<Rating> GetUserRating(int userId)
        {
            var relationship = (from x in db.RatingToUserToGames
                                    where x.UserId == userId
                                    select x);
            List<Rating> returnList = new List<Rating>();
            foreach (var rating in relationship)
            {
                Rating temp = (from x in db.Ratings
                               where x.id == rating.RatingId
                               select x).Single();
                returnList.Add(temp);
            }
            return returnList;
        }
    }
}